<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ajax</title>
</head>

<body>
    <!-- <form action="https://www.baidu.com" method="GET">
        <input type="text">
    </form> -->
    <button id="myButton">点我</button>
    <script>
        myButton.onclick = function (e) {
            let request = new XMLHttpRequest()
            request.open('GET', '/xxx') // 配置request
            request.send()
            request.onreadystatechange = () => {
                if (request.readyState === 4) {
                    console.log('请求响应都完毕了')
                    console.log(request.status)
                    if (request.status >= 200 && request.status < 300) {
                        console.log('说明请求成功')
                        console.log(typeof request.responseText)
                        console.log(request.responseText)
                        let string = request.responseText
                        // 把符合 JSON 语法的字符串
                        // 转换成 JS 对应的值
                        let object = window.JSON.parse(string)
                        // JSON.parse 是浏览器提供的
                        console.log(typeof object)
                        console.log(object)
                        console.log('object.note')
                        console.log(object.note)

                    } else if (request.status >= 400) {
                        console.log('说明请求失败')
                    }
                }
            }
        }
        //原生JS实现


        //封装成jQ
        /*window.jQuery = function () { }
        window.$ = window.jQuery
        $.ajax = function (options) {
            let request = new XMLHttpRequest()
            let method = options.method
            let url = options.url
            let body = options.body
            let successFn = options.successFn
            let failFn = options.failFn
            console.log(request)
            request.open(method, url)
            request.onreadystatechange = () => {
                if (request.readyState === 4) {
                    if (request.status >= 200 && request.status < 300) {
                        successFn.call(undefined, request.responseText)
                    } else if (request.status >= 400) {
                        failFn.call(undefined, request)
                    }
                }
            }
            request.send(body)
        }
        myButton.addEventListener('click', () => {
            let promise = $.ajax({
                method: 'POST',
                url: './xxx',
                body: 'a=1&b=2',
                successFn: (responseText) => { console.log(1) },
                failFn: (request) => { console.log(2) }
            })
        })
        */
    </script>
</body>

</html>